//
// Created by user on 2022/3/15.
//
#include <iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
    };

ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode *curr = head;
    int m = 0;
    while (curr){
        m++;
        curr = curr->next;
    }
    if (m<n)return head;
    int k = m-n;
    ListNode *dummy = new ListNode(-1);
    dummy->next = head;
    curr = head;
    ListNode *prev = dummy;

    for (int i = 0; i < k; ++i) {
        curr = curr->next;
        prev = prev->next;
    }
    prev->next = curr->next;

    return dummy->next;

}